import axios from 'axios';
import router from '@/router'
// import { showFailToast } from 'vant'
import { ElMessage } from 'element-plus'


const service = axios.create({
    timeout: 120000
});

//http request 拦截器
service.interceptors.request.use(
    config => {
        // 获取token
        const token = localStorage.getItem('token');
        const userId = localStorage.getItem('userid');
        // const token = store.getters.getToken;
        // 设置参数格式
        if (!config.headers['Content-Type']) {
            config.headers = {
                'Content-Type': 'application/json',
            };
        }
        // 添加token到headers
        if (token) {
            config.headers.token = token;
            if(userId) {
                config.headers.userId = userId;
            }
        }
        // 鉴权参数设置
        if (config.method === 'get') {
            //get请求下 参数在params中，其他请求在data中
            config.params = config.params || {};
            // let json = JSON.parse(JSON.stringify(config.params));
            //一些参数处理
        } else {
            config.data = config.data || {};
            //一些参数处理
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

//http response 拦截器
service.interceptors.response.use(
    response => {
        if(response.status == 401) {
            // showFailToast('登录已失效，请重新登录');
            ElMessage({
                message: '登录已失效，请重新登录',
                type: 'error',
            });
            // router.push({name: 'login'});
            router.push({
                path: '/login',
            });
        } else {
            return response;
        }
    },
    error => {
        //一些统一code的返回处理
        if (error.response) {
            switch (error.response.status) {
                case 400:
                    // Message({
                    //     message: '参数异常:',
                    //     type: 'error'
                    // });
                    // showFailToast('参数异常');
                    ElMessage({
                        message: '参数异常',
                        type: 'error',
                    });
                    break;
                case 401:
                    // 登录验证
                    // Message({
                    //     message: '登录已失效，请重新登录',
                    //     type: 'error'
                    // })
                    // showFailToast('登录已失效，请重新登录');
                    ElMessage({
                        message: '登录已失效，请重新登录',
                        type: 'error',
                    });
                    // router.push({name: 'login'});
                    router.push({
                        path: '/login',
                    });
            }
        }
        return Promise.reject(error)
    }
);

export const ajax = {

    /**
     * 封装get方法
     * @param url
     * @param params
     * @returns {Promise}
     */
    get(url, params = {}, isnHideErr ) {
        if (Object.keys(params).length !== 0) {
            params = {
              ...params,
              timestamp: (new Date()).valueOf()
            }
        } else {
            params = {
                timestamp: (new Date()).valueOf()
            }
        }
        return new Promise((resolve, reject) => {
            service.get(url, {
                params: params
            })
                .then(response => {
                    resolve(response.data);
                    if (response.data.code === 200) {
                        //返回成功处理  这里传的啥 后续调用的时候 res就是啥
                    } else if(response.data.code === 401) {
                        // showFailToast('登录已失效，请重新登录');
                        ElMessage({
                            message: '登录已失效，请重新登录',
                            type: 'error',
                        });
                        // router.push({name: 'login'});
                        router.push({
                            path: '/login',
                        });
                    } else {
                        // isnHideErr && Message({
                        //     message: response.data.message,
                        //     type: 'error'
                        // })
                        // isnHideErr && showFailToast(response.data.message);
                        isnHideErr && ElMessage({
                            message: response.data.message,
                            type: 'error',
                        });
                    }
                })
                .catch(err => {
                    reject(err);
                })
        })
    },



    /**
     * 封装post请求
     * @param url
     * @param data
     * @returns {Promise}
     */

    post(url, data = {}, isnHideErr) {
        return new Promise((resolve, reject) => {
            service.post(url, data)
                .then(response => {
                    resolve(response);
                    if (response.data.code === 200) {
                        //返回成功处理  这里传的啥 后续调用的时候 res就是啥
                        // isnHideErr && Message({
                        //     message: response.data.message,
                        //     type: 'success'
                        // })
                    } else if(response.data.code === 401) {
                        // showFailToast('登录已失效，请重新登录');
                        ElMessage({
                            message: '登录已失效，请重新登录',
                            type: 'error',
                        });
                        // router.push({name: 'login'});
                        router.push({
                            path: '/login',
                        });
                    }  else {
                        // isnHideErr && Message({
                        //     message: response.data.message,
                        //     type: 'error'
                        // })
                        // isnHideErr && showFailToast(response.data.message);
                        isnHideErr && ElMessage({
                            message: response.data.message,
                            type: 'error',
                        });
                    }
              }, err => {
                    reject(err);
              })
        })
    },

    /**
     * uploadFile
     * @param url
     * @param params
     * @returns {Promise}
     */
      uploadFile(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.post(url, params, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            })
                .then(response => {
                    resolve(response);
                })
                .catch(function (error) {
                    if (error.response) {
                        switch (error.response.status) {
                            case 400:
                                // showFailToast('参数异常');
                                ElMessage({
                                    message: '参数异常',
                                    type: 'error',
                                });
                                break;
                            case 401:
                                // 登录验证
                                // showFailToast('登录已失效，请重新登录');
                                ElMessage({
                                    message: '登录已失效，请重新登录',
                                    type: 'error',
                                });
                                // router.push({name: 'login'});
                                router.push({
                                    path: '/login',
                                });
                                break;
                            default:
                                reject(error);
                        }
                    } else {
                        reject(error);
                    }
                });
        })
    },

    /**
     * formData
     * @param url
     * @param params
     * @returns {Promise}
     */
    formData(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.post(url, params, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            })
                .then(response => {
                    // resolve(response);
                    resolve(response.data);
                })
                .catch(function (error) {
                    if (error.response) {
                        switch (error.response.status) {
                            case 400:
                                // showFailToast('参数异常');
                                ElMessage({
                                    message: '参数异常',
                                    type: 'error',
                                });
                                break;
                            case 401:
                                // 登录验证
                                // showFailToast('登录已失效，请重新登录');
                                ElMessage({
                                    message: '登录已失效，请重新登录',
                                    type: 'error',
                                });
                                // router.push({name: 'login'});
                                router.push({
                                    path: '/login',
                                });
                                break;
                            default:
                                reject(error);
                        }
                    } else {
                        reject(error);
                    }
                });
        })
    }




    
};